package proyecto2a;

import java.util.Iterator;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JPanel;

public class Automove extends Thread {
	private JLabel label;
	private JPanel panel;
	private Vector<Nave> navesenemigas;
	private JLabel puntaje;
	
	public Automove( JLabel label, JPanel panel, Vector<Nave> naves, JLabel puntaje) {
		this.label = label;
		this.panel = panel;
		this.navesenemigas = naves;
		this.puntaje=puntaje;
	}
	
	private boolean hayImpacto(JLabel p1, JLabel p2) {
		if (p1.getBounds().intersects(p2.getBounds()))
				return true;
		else
			return false;
	}
	
	public void naveColisionada() {
		Iterator<Nave>enemigas=navesenemigas.iterator();
		while(enemigas.hasNext()){
			Nave it=enemigas.next();
			if(hayImpacto(label,it)){
				panel.remove(it);
				panel.remove(label);
				enemigas.remove();
				panel.repaint();
				int i=(Integer.parseInt(puntaje.getText()))+1;
				String ret= Integer.toString(i);
				puntaje.setText(ret);
			}
		}
	}
	
	public void run() {
		for (int i = this.label.getLocation().y; i>=0; i++) {
			/** .. si se salen de los margenes, elimina la bala */
			if (this.label.getLocation().y< 0
					|| (this.label.getLocation().y > this.panel.getHeight())){
				this.panel.remove(label);
			}
			/** si no, mueve el disparo */
			else{
				try {
					this.label.setLocation(this.label.getLocation().x,this.label.getLocation().y-20);
					synchronized(navesenemigas){
						naveColisionada();
					}
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
			}
			
		}
		this.stop();
	}
}
